/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.institution.bean.*;
import com.koron.institution.mapper.*;
import com.koron.institution.service.api.LawCorpService;
import com.koron.institution.uitls.BaseEntityUtil;
import com.koron.institution.uitls.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@PropertySource("classpath:institution.properties")
public class LawCorpServiceImpl implements LawCorpService, InitializingBean, AfterApprovalService {

    private final static  Logger logger = LoggerFactory.getLogger(LawCorpServiceImpl.class);

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Value("${law_corp_add_confirm}")
    private String lawCorpAddConfirm;

    @Value("${law_corp_discard_confirm}")
    private String lawCorpDiscardConfirm;

    @Value("${institution_file_template_key}")
    private String institutionFileTemplateKey;

    @Value("${law_institution_file_template_key}")
    private String lawInstitutionFileTemplateKey;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    MessageBean<LawCond> checkAndProduceCond(String fileName, String corpCode, String categoryId, Integer page,
                                             Integer pageSize) {
        MessageBean<LawCond> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), LawCond.class);
        LawCond cond = new LawCond();
        if (StringUtils.isNotBlank(fileName)) {
            cond.setFileName(fileName);
        }
        if (StringUtils.isNotBlank(categoryId)) {
            cond.setCategoryId(categoryId);
        }

        if (page != null && page > 0 && pageSize != null && pageSize > 0) {
            cond.setPage(page);
            cond.setPageSize(pageSize);
            cond.setStart((page - 1) * pageSize);
        }
        if (StringUtils.isBlank(corpCode)) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
            return msg;
        } else {
            cond.setCorpCode(corpCode);
        }

        msg.setData(cond);
        return msg;
    }

    @Override
    public MessageBean<?> getList(String fileName, String corpCode, Integer state, String categoryId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            MessageBean<LawCond> condMessageBean = checkAndProduceCond(fileName, corpCode, categoryId,
                    page, pageSize);
            if (condMessageBean.getCode() != 0) {
                return condMessageBean;
            }
            LawCond cond = condMessageBean.getData();
            cond.setState(state);
            LawCorpMapper mapper = factory.getMapper(LawCorpMapper.class);
            List<LawCorp> list = mapper.getListByCond(cond);
            int total = mapper.getTotalByCond(cond);
            DataBean<LawCorp> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(cond.getPage());
            dataBean.setPageSize(cond.getPageSize());
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> selectList(String corpCode, String categoryId, String fileName, Integer page,
                                     Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            LawMapper lawMapper = factory.getMapper(LawMapper.class);
//            List<LawCorp> lawCorpList = mapper.selectList(corpCode);
            MessageBean<LawCond> condMessageBean = checkAndProduceCond(fileName, corpCode, categoryId,
                    page, pageSize);
            if (condMessageBean.getCode() != 0) {
                return condMessageBean;
            }
            LawCond cond = condMessageBean.getData();
//            List<LawCorp> list = mapper.getListByCond(cond);
            List<Law> lawList = lawMapper.getSelectList(cond);
            int total = lawMapper.getSelectTotal(cond);
//            if (lawList != null && !lawList.isEmpty()) {
//                List<Law> selectList = new ArrayList<>();
//                for (Law law : lawList) {
//                    if (law == null) {
//                        continue;
//                    }
//                    if (lawCorpList != null && !lawCorpList.isEmpty()) {
//                        if (!lawCorpList.stream().anyMatch(lawCorp -> law.getCode().equals(lawCorp == null ? null : lawCorp.getLawCode()))) {
//                            selectList.add(law);
//                        }
//                    } else {
//                        selectList.add(law);
//                    }
//                }
//
//            }
            DataBean<Law> dataBean = new DataBean<>();
            dataBean.setList(lawList);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(cond.getPage());
            dataBean.setPageSize(cond.getPageSize());
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> saveOrCommit(String lawCorpListStr, StaffBean user, String approverCodeListStr, Integer operationType) {
        MessageBean<InstitutionFile> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), InstitutionFile.class);

        SessionFactory factory = new SessionFactory();
        try {
            LawCategoryMapper categoryMapper = factory.getMapper(LawCategoryMapper.class);
            LawCorpCategoryMapper lawCorpCategoryMapper = factory.getMapper(LawCorpCategoryMapper.class);
            LawCorpMapper mapper = factory.getMapper(LawCorpMapper.class);
            LawCorpHistoryMapper historyMapper = factory.getMapper(LawCorpHistoryMapper.class);
            LawMapper lawMapper = factory.getMapper(LawMapper.class);
            List<LawCorp> lawCorpList = JSONObject.parseArray(lawCorpListStr, LawCorp.class);

            if (lawCorpList == null && lawCorpList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_LAW_CORP.getCode());
                msg.setDescription(BusinessCode.EMPTY_LAW_CORP.getDescription());
                return msg;
            }
            List<String> idList = new ArrayList<>();
            for (LawCorp lawCorp : lawCorpList) {
                if (StringUtils.isBlank(lawCorp.getCorpCode())) {
                    msg.setCode(BusinessCode.EMPTY_CORP_CODE.getCode());
                    msg.setDescription(BusinessCode.EMPTY_CORP_CODE.getDescription());
                    factory.close(false);
                    return msg;
                }

                //是否传入了法规库的法规code;
                if (StringUtils.isBlank(lawCorp.getLawCode())) {
                    msg.setCode(BusinessCode.EMPTY_LAW_CODE.getCode());
                    msg.setDescription(BusinessCode.EMPTY_LAW_CODE.getDescription());
                    factory.close(false);
                    return msg;
                } else {
                    //判断法规库是否存在对应的法规
                    List<Law> lawList = lawMapper.queryLawByCode(lawCorp.getLawCode());
                    if (lawList == null || lawList.isEmpty()) {
                        msg.setCode(BusinessCode.LAW_NOT_EXIST.getCode());
                        msg.setDescription(BusinessCode.LAW_NOT_EXIST.getDescription());
                        factory.close(false);
                        return msg;
                    }
                    //判断法规库的法规是否废除
                    Law law = lawList.get(0);
                    if (law.getState() == 4) {
                        msg.setCode(BusinessCode.LAW_DISCARDED.getCode());
                        msg.setDescription(BusinessCode.LAW_DISCARDED.getDescription());
                        factory.close(false);
                        return msg;
                    }
                    //判断该水司是否引入了该法规
                    List<LawCorp> existList = mapper.checkExist(lawCorp);
                    if (existList != null && !existList.isEmpty() && existList.stream().anyMatch(lc -> !lc.getId().equals(lawCorp.getId()))) {
                        msg.setCode(BusinessCode.LAW_CORP_EXIST.getCode());
                        msg.setDescription(BusinessCode.LAW_CORP_EXIST.getDescription());
                        factory.close(false);
                        return msg;
                    }
//                    String categoryId = setCategory(lawCorpCategoryMapper, categoryMapper, lawCorp, user, lawCorp.getCategoryId());
//                    if (categoryId == null) {
//                        msg.setCode(BusinessCode.ERROR_CREATE_CATEGORY.getCode());
//                        msg.setDescription(BusinessCode.ERROR_CREATE_CATEGORY.getDescription());
//                        factory.close(false);
//                        return msg;
//                    }
                   // lawCorp.setCategoryId(categoryId);
                }
                //判断是否传入了目录
                if (StringUtils.isBlank(lawCorp.getCategoryId())) {
                    msg.setCode(BusinessCode.EMPTY_LAW_CATEGORY_ID.getCode());
                    msg.setDescription(BusinessCode.EMPTY_LAW_CATEGORY_ID.getDescription());
                    factory.close(false);
                    return msg;
                }
                if (operationType == 0) {
                    lawCorp.setState(5);
                } else {
                    lawCorp.setState(1);
                }
                if (StringUtils.isBlank(lawCorp.getId())) {
                    BaseEntityUtil.setAddBaseProperties(lawCorp, user);
                    mapper.insert(lawCorp);
                } else {
                    LawCorp lawCorpOld = mapper.selectByPrimaryKey(lawCorp.getId());
                    if (lawCorpOld == null) {
                        BaseEntityUtil.setAddBaseProperties(lawCorp, user);
                        mapper.insert(lawCorp);
                    } else {
                        BaseEntityUtil.setUpdateBaseProperties(lawCorp, user);
                        mapper.updateByPrimaryKeySelective(lawCorp);
                    }
                }
                if (operationType == 1) {
                    //保存新增审批记录
                    //转换成history
                    LawCorpHistory history = translateToHistory(lawCorp);
                    history.setId(DefaultIdGenerator.getInstance().generateLongId());
                    history.setState(1);
                    history.setHistoryFlag(0);
                    historyMapper.insert(history);
                    idList.add(history.getId());
                }

            }
            if (operationType == 1) {
                if (StringUtils.isBlank(approverCodeListStr)) {
                    msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                    msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                    factory.close(false);
                    return msg;
                }
                List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
                if (approverCodeList == null || approverCodeList.isEmpty()) {
                    msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                    msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                    factory.close(false);
                    return msg;
                }
                // 构造audit
                Audit audit = new Audit();
                Date now = new Date();
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setUpdateUser(user.getName());
                audit.setUpdateTime(now);
                audit.setAddUser(user.getName());
                audit.setAddTime(now);
                audit.setFlowType(1);
                audit.setOperation(1);
                audit.setTarget(LawCorpServiceImpl.class.getName());
                audit.setFlowName(lawCorpAddConfirm);
                //audit.setTitle( snap.getUpdateUser() + "提交了一份随手拍待确认");
                audit.setTitle(lawCorpAddConfirm);
                audit.setCorpCode(user.getDepartmentCode());
                audit.setInitiatorCode(user.getCode());
                audit.setDescription(lawCorpAddConfirm);
                audit.setState(1);
                audit.setTemplateKey(lawInstitutionFileTemplateKey);
                // 模板组code
                audit.setSetCode("institution_manage");
                audit.setInitiatorAccount(user.getUserid());
                audit.setBusinessIds(new Gson().toJson(idList));
                Map<String, Object> businessMap = new HashMap<>();
                StringBuilder codes = new StringBuilder();
                for (String code : approverCodeList) {
                    codes.append(code.split("_")[0]).append(",");
//                    codes.append("1-").append(code.split("_")[0]).append(",");
                }
                businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
                if (!flowManagement.initFlow(user, audit, businessMap)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("提交法规制度失败");
                } else {
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("提交法规制度成功");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

//    String setCategory(LawCorpCategoryMapper lawCorpCategoryMapper, LawCategoryMapper categoryMapper, LawCorp lawCorp, StaffBean user, String id) throws Exception {
//        LawCategory entity = categoryMapper.selectByPrimaryKey(id);
//       LawCorpCategory lawCorpCategory=lawCorpCategoryMapper.selectByPrimaryKey(id);
//       if ((entity==null||entity.getPid()==null)&&(lawCorpCategory==null||lawCorpCategory.getPid()==null)){
//           return null;
//       }
//       if (lawCorpCategory!=null){
//           return lawCorpCategory.getId();
//       }
//       if(!"root".equals(entity.getPid())){
//            String pid = setCategory(lawCorpCategoryMapper, categoryMapper, lawCorp, user, entity.getPid());
//            if (pid == null) {
//                return null;
//            }
//            //查询目录名称是否已存在
//            LawCorpCategory cond = new LawCorpCategory();
//            cond.setCategoryName(entity.getCategoryName());
//            cond.setCorpCode(lawCorp.getCorpCode());
//            cond.setPid(pid);
//            List<LawCorpCategory> lawCorpCategoryList = lawCorpCategoryMapper.getCategoryListByCond(cond);
//            if (lawCorpCategoryList != null && !lawCorpCategoryList.isEmpty()) {
//                return lawCorpCategoryList.get(0).getId();
//            } else {
//                LawCorpCategory lawCorpCategoryNew = new LawCorpCategory();
//                lawCorpCategoryNew.setCorpCode(lawCorp.getCorpCode());
//                lawCorpCategoryNew.setState(0);
//                lawCorpCategoryNew.setPid(pid);
//                lawCorpCategoryNew.setCategoryName(entity.getCategoryName());
//                lawCorpCategoryNew.setIndicationIndex(entity.getIndicationIndex());
//                BaseEntityUtil.setAddBaseProperties(lawCorpCategoryNew, user);
//                lawCorpCategoryMapper.insert(lawCorpCategoryNew);
//                return lawCorpCategoryNew.getId();
//            }
//        } else {
//            //查询目录名称是否已存在
//            LawCorpCategory cond = new LawCorpCategory();
//            cond.setCategoryName(entity.getCategoryName());
//            cond.setCorpCode(lawCorp.getCorpCode());
//            cond.setPid(entity.getPid());
//            List<LawCorpCategory> lawCorpCategoryList = lawCorpCategoryMapper.getCategoryListByCond(cond);
//            if (lawCorpCategoryList != null && !lawCorpCategoryList.isEmpty()) {
//                return lawCorpCategoryList.get(0).getId();
//            } else {
//                LawCorpCategory lawCorpCategoryNew = new LawCorpCategory();
//                lawCorpCategoryNew.setCorpCode(lawCorp.getCorpCode());
//                lawCorpCategoryNew.setState(0);
//                lawCorpCategoryNew.setCategoryName(entity.getCategoryName());
//                lawCorpCategoryNew.setIndicationIndex(entity.getIndicationIndex());
//                lawCorpCategoryNew.setPid("root");
//                BaseEntityUtil.setAddBaseProperties(lawCorpCategoryNew, user);
//                lawCorpCategoryMapper.insert(lawCorpCategoryNew);
//                return lawCorpCategoryNew.getId();
//            }
//        }
//    }

    LawCorpHistory translateToHistory(LawCorp lawCorp) {
        LawCorpHistory history = new LawCorpHistory();
        BeanUtils.copyProperties(lawCorp, history);
        history.setNewLawCorpId(lawCorp.getId());
        return history;
    }

    @Override
    public MessageBean<?> discard(String lawCorpId, StaffBean user, String approverCodeListStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);

        SessionFactory factory = new SessionFactory();
        try {
            LawCorpMapper mapper = factory.getMapper(LawCorpMapper.class);
            LawCorpHistoryMapper historyMapper = factory.getMapper(LawCorpHistoryMapper.class);
            //根据id获取制度记录
            Date now = new Date();
            LawCorp lawCorp = mapper.selectByPrimaryKey(lawCorpId);
            if (lawCorp == null) {
                msg.setCode(BusinessCode.LAW_CORP_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.LAW_CORP_NOT_EXIST.getDescription());
                factory.close();
                return msg;
            }
            if (lawCorp.getState() == 5) {
                mapper.deleteByPrimaryKey(lawCorp.getId());
                return msg;
            }
            if (StringUtils.isBlank(approverCodeListStr)) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                return msg;
            }
            List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
            if (approverCodeList == null || approverCodeList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                return msg;
            }
            lawCorp.setUpdateUser(user.getCode());
            lawCorp.setUpdateUserName(user.getName());
            lawCorp.setUpdateTime(now);
            lawCorp.setState(3);
            mapper.updateByPrimaryKeySelective(lawCorp);
            //添加一条审批记录
            LawCorpHistory history = translateToHistory(lawCorp);
            history.setState(3);
            history.setHistoryFlag(1);
            history.setId(DefaultIdGenerator.getInstance().generateLongId());
            historyMapper.insert(history);
            //审批
            Audit audit = new Audit();

            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(2);
            audit.setTarget(LawCorpServiceImpl.class.getName());
            audit.setFlowName(lawCorpDiscardConfirm);
            //audit.setTitle( snap.getUpdateUser() + "提交了一份随手拍待确认");
            audit.setTitle(lawCorpDiscardConfirm);
            audit.setCorpCode(user.getDepartmentCode());
            audit.setInitiatorCode(user.getCode());
            audit.setDescription(lawCorpDiscardConfirm);
            audit.setState(1);
            audit.setTemplateKey(institutionFileTemplateKey);
            // 模板组code
            audit.setSetCode("institution_manage");
            audit.setInitiatorAccount(user.getUserid());
            List<String> idList = new ArrayList<>();
            idList.add(history.getId());
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append(code.split("_")[0]).append(",");
//                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("废除公司法规失败");
            } else {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("废除公司法规成功");
                factory.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }


    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
                    LawCorpHistoryMapper mapper = factory.getMapper(LawCorpHistoryMapper.class);
                    List<LawCorpHistory> list = mapper.queryListByIds(idList);
                    msg.setData(list);
                }
            } else {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_ID.getDescription());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(LawCorpServiceImpl.class.getName(), this);
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        LawCorpMapper mapper = factory.getMapper(LawCorpMapper.class);
                        LawCorpHistoryMapper historyMapper = factory.getMapper(LawCorpHistoryMapper.class);

                        LawCorpHistory history = historyMapper.selectByPrimaryKey(planId);
                        if (history != null) {
                            LawCorp lawCorp = mapper.selectByPrimaryKey(history.getNewLawCorpId());
                            if (lawCorp != null) {
                                if (lawCorp.getState() == 4) {
                                    continue;
                                }
                                lawCorp.setState(0);
                                mapper.updateByPrimaryKeySelective(lawCorp);

                                history.setState(0);
                                history.setHistoryFlag(0);
                                historyMapper.updateByPrimaryKeySelective(history);

                                Calendar now = Calendar.getInstance();
                                Integer year = now.get(Calendar.YEAR);
                                ConformanceAssessment conformanceAssessment = new ConformanceAssessment();
                                conformanceAssessment.setState(0);
                                conformanceAssessment.setCorpCode(lawCorp.getCorpCode());
                                conformanceAssessment.setConformanceYear(year);
                                conformanceAssessment.setInstitutionCode(lawCorp.getLawCode());
                                conformanceAssessment.setSuitDept(null);
                                conformanceAssessment.setConformanceFlag(1);
                                conformanceAssessment.setAddUser(lawCorp.getAddUser());
                                conformanceAssessment.setUpdateUser(lawCorp.getUpdateUser());
                                conformanceAssessment.setAddTime(lawCorp.getAddTime());
                                conformanceAssessment.setUpdateTime(lawCorp.getUpdateTime());
                                conformanceAssessment.setAddUserName(lawCorp.getAddUserName());
                                conformanceAssessment.setUpdateUserName(lawCorp.getUpdateUserName());
                                conformanceAssessment.setId(DefaultIdGenerator.getInstance().generateLongId());
                                ConformanceAssessmentMapper conformanceMapper = factory.getMapper(ConformanceAssessmentMapper.class);
                                conformanceMapper.insert(conformanceAssessment);
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        LawCorpMapper mapper = factory.getMapper(LawCorpMapper.class);
                        LawCorpHistoryMapper historyMapper = factory.getMapper(LawCorpHistoryMapper.class);
                        LawCorpHistory history = historyMapper.selectByPrimaryKey(planId);
                        if (history != null) {
                            LawCorp lawCorp = mapper.selectByPrimaryKey(history.getNewLawCorpId());
                            if (lawCorp != null) {
                                lawCorp.setState(4);
                                mapper.updateByPrimaryKeySelective(lawCorp);
                            }
                            history.setState(0);
                            history.setHistoryFlag(1);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }

            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void processDiscard(Audit audit) {
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (audit.getOperation() == 1) {
                processDiscardAdd(idList);
            } else if (audit.getOperation() == 2) {
                processDiscardDel(idList);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }


    private void processDiscardAdd(List<String> idList) {
        SessionFactory factory = new SessionFactory();
        try {
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        LawCorpMapper mapper = factory.getMapper(LawCorpMapper.class);
                        LawCorpHistoryMapper historyMapper = factory.getMapper(LawCorpHistoryMapper.class);
                        LawCorpHistory history = historyMapper.selectByPrimaryKey(planId);
                        if (history != null) {
                            LawCorp lawCorp = mapper.selectByPrimaryKey(history.getNewLawCorpId());
                            if (lawCorp.getState() == 4) {
                                continue;
                            }
                            lawCorp.setState(5);
                            mapper.updateByPrimaryKeySelective(lawCorp);
                            history.setState(4);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        } finally {
            if (null != factory)
                factory.close();
        }
    }

    private void processDiscardDel(List<String> idList) {
        SessionFactory factory = new SessionFactory();
        try {
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        LawCorpMapper mapper = factory.getMapper(LawCorpMapper.class);
                        LawCorpHistoryMapper historyMapper = factory.getMapper(LawCorpHistoryMapper.class);

                        LawCorpHistory history = historyMapper.selectByPrimaryKey(planId);
                        if (history != null) {
                            LawCorp lawCorp = mapper.selectByPrimaryKey(history.getNewLawCorpId());
                            if (lawCorp != null) {
                                lawCorp.setState(0);
                                mapper.updateByPrimaryKeySelective(lawCorp);
                            }
                            history.setState(4);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }

            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
